package com.rchat.pocmini.activity.fragment.groups;

import android.text.TextUtils;
import android.widget.Toast;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.airtalkee.sdk.AirtalkeeChannel;
import com.airtalkee.sdk.AirtalkeeSessionManager;
import com.airtalkee.sdk.OnChannelListener;
import com.airtalkee.sdk.entity.AirChannel;
import com.airtalkee.sdk.entity.AirContact;
import com.airtalkee.sdk.entity.AirSession;
import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.aso.common.utils.ToastUtils;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.bean.GroupBean;
import com.rchat.pocmini.activity.groupsselect.view.GroupSelectBean;
import com.rchat.pocmini.bean.AccountBean;
import com.rchat.pocmini.bean2eventbus.BluetoothBean;
import com.rchat.pocmini.bean2eventbus.EventBusAccountBean;
import com.rchat.pocmini.bean2eventbus.LocationReportChannelBean;
import com.rchat.pocmini.bean2eventbus.UpdateGroupBean;
import com.rchat.pocmini.bluetooth.BTService;
import com.rchat.pocmini.channel.PocAirtalkeeChannel;
import com.rchat.pocmini.session.PocAirtalkeeSessionManager;
import com.rchat.pocmini.util.SPUtil;
import com.rchat.pocmini.util.Sound;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by itsdf07 on 2017/8/24.
 */

public class GroupsPresenterImpl extends GroupsContract.Presenter implements OnChannelListener {
    /**
     * 群组ID
     */
    public static final String KEY_GROUPID = "groupId";
    /**
     * 频道监听数上线大小
     */
    public final int SESSION_MAX_COUNT = 5;

    private PocAirtalkeeChannel mPocAirtalkeeChannel;
    private PocAirtalkeeSessionManager mPocAirtalkeeSessionManager;

    /**
     * 群组列表数据源
     */
    private ArrayList<GroupBean> mGroupsData;

    /**
     * 当前账号创建的群组列表数据源
     */
    private ArrayList<GroupSelectBean> mGroupsCreateData;
    /**
     * 监听中的群组数据源
     */
    private ArrayList<GroupBean> mChannelListeningData;

    /**
     * 上锁的频道
     */
    private String lockedChannel;

    /**
     * 当前账号Id
     */
    String mUserId;

    @Override
    public void onPStart() {
        /**
         * @author sudf
         * @date 2017.8.29
         * EventBus的注册不能随界面的展示和挂起进行注册和反注册，
         * 比如在创建群组界面，创建成功后，就导致EventBus无法接受消息，引起列表无法刷新
         */
        EventBus.getDefault().register(this);
        mUserId = AirtalkeeAccount.getInstance().getUserId();
        mChannelListeningData = new ArrayList<>();
        initPocAirtalkeeChannel();
        mPocAirtalkeeSessionManager = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance();
    }

    @Override
    public void onPDestroy() {
        EventBus.getDefault().unregister(this);
        super.onPDestroy();
    }

    /**
     * 统一群组界面的事件分发
     *
     * @param bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusUpdateGroups(UpdateGroupBean bean) {
        if (bean == null || !bean.isTarget(this.getClass())) {
            return;
        }
        ALog.d("currentEvent = %s", bean.getCurrentEvent());
        switch (bean.getCurrentEvent()) {
            case UpdateGroupBean.EVENT_GROPUITEM_MEDIASTATELISTEN:
                onMediaStateListen(bean.getAirSession(), bean.getAirContact());
                break;
            case UpdateGroupBean.EVENT_GROPUITEM_MEDIASTATELISTENEND:
                onMediaStateListenEnd(bean.getAirSession());
                break;
            case UpdateGroupBean.EVENT_GROPUITEM_MEDIASTATETALK:
                onMediaStateTalk(bean.getAirSession());
                break;
            case UpdateGroupBean.EVENT_GROPUITEM_MEDIASTATETALKEND:
                onMediaStateTalkEnd(bean.getAirSession(), bean.getReason());
                break;
            case UpdateGroupBean.EVENT_GROPUITEM_UPDATE:
                onUpdateGroupItem(bean.getAirSession());
                break;
            case UpdateGroupBean.EVENT_GROPULIST_UPDATE:
                onUpdateGroupList();
            default:
                break;
        }
    }


    /**
     * 1、获取账号信息
     * 2、刷新账号昵称
     *
     * @param bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusRequestAccount(EventBusAccountBean bean) {
        if (null == bean || !bean.isTarget(this.getClass())) {
            return;
        }
        ALog.d("currentEvent = %s", bean.getCurrentEvent());
        switch (bean.getCurrentEvent()) {
            case EventBusAccountBean.EVENT_ACCOUNT_DATE:
                onRequestAccountStatus();
                break;
            case EventBusAccountBean.EVENT_CHANGE_NICKNAME:
                if (mView == null) {
                    break;
                }
                mView.updateNickName(TextUtils.isEmpty(PocAccount.getNewUserName()) ?
                        PocAccount.getUserName() : PocAccount.getNewUserName());
                break;
            default:
                break;
        }
    }

    @Override
    public void
    onChannelListGet(boolean isOk, List<AirChannel> channelList) {
//        mView.dismissLoading();
        ALog.d("isOk = %s,channelList.size = %s", isOk, channelList.size());
        Collections.reverse(channelList);
        /**
         * @author dfsu
         * @date 2017.07.17
         * 需在每次获取群组列表时更新当前锁定的频道，否则在群组删除重新获取列表时，
         * lockedChannel依然是第一次初始化的频道
         */
        lockedChannel = (String) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_LOCKEDCHANNEL, "");

        initData(channelList);

        mView.updateList(mGroupsData);

    }

    @Override
    public void onChannelMemberListGet(String s, List<AirContact> list) {

    }

    @Override
    public void onChannelOnlineCount(LinkedHashMap<String, Integer> linkedHashMap) {

    }

    @Override
    public void onChannelPersonalCreateNotify(AirChannel airChannel) {

    }

    @Override
    public void onChannelPersonalDeleteNotify(AirChannel airChannel) {

    }

    @Override
    public void onChannelMemberAppendNotify(AirChannel airChannel, List<AirContact> list) {

    }

    @Override
    public void onChannelMemberDeleteNotify(AirChannel airChannel, List<AirContact> list) {

    }

    @Override
    public void onChannelMemberUpdateNotify(AirChannel airChannel, List<AirContact> list) {

    }

    @Override
    public void onChannelMemberUpdateNotify(AirChannel airChannel, AirContact airContact) {

    }

    /**
     * 请求账号信息：会员状态
     */
    private void onRequestAccountStatus() {
        mModel.requestAccountStatus(PocAccount.getUserId(), new HttpCallbackImpl<AccountBean>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(AccountBean bean) {
                if (mView == null) {
                    return;
                }
//                ToastUtils.showToast(mActivity, "重启后可使用PTT键");
                PocAccount.setExpireDate(bean.getData().getExpireTime());
                mView.updateExpireData(bean.getData().getExpireTime());
                if (bean.getData().getStatus() != (int) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, 0)) {
                    SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, bean.getData().getStatus());
                    SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_IS_ENABLEPTT, bean.getData().getStatus() == 2 ? 1 : 0);
                    BluetoothBean bluetoothBean = new BluetoothBean();
                    bluetoothBean.setCurrentEvent(BluetoothBean.EVENT_ENABLE_PTT);
                    bluetoothBean.setTarget(this.getClass(), BTService.class, "onBluetoothEventBus");
                    EventBus.getDefault().post(bluetoothBean);
                }
                onUpdateGroupList();
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                if (mView == null) {
                    return;
                }
                mView.showNetError(bean.getDesc());
            }

            @Override
            public void onFinish() {
                if (mView == null) {
                    return;
                }
            }
        });
    }

    //-------------------------------MediaListener

    private void onMediaStateTalk(AirSession airSession) {
        //本人讲话开始
        for (int i = 0; i < mGroupsData.size(); i++) {
            if (mGroupsData.get(i).getGroupId().equals(airSession.getChannel().getId())) {
                mGroupsData.get(i).setWhoIsTalking("您正在讲话");
                mGroupsData.get(i).setShowTalking(true);
                mView.updateList(mGroupsData);
            }
        }
    }

    public void onMediaStateTalkEnd(AirSession airSession, int reason) {
        if (reason == AirtalkeeSessionManager.TALK_FINISH_REASON_SPEAKING_FULL || reason == AirtalkeeSessionManager.TALK_FINISH_REASON_TIMEOUT) {
            Sound.playSound(Sound.PLAYER_MEDIA_ERROR, mActivity);
            Toast.makeText(mActivity, "\"" + airSession.getDisplayName() + "\"" + "频道有人正在讲话，请稍后再试！", Toast.LENGTH_SHORT).show();
        } else {
            Sound.playSound(Sound.PLAYER_MEDIA_ME_OFF, mActivity);
            for (int i = 0; i < mGroupsData.size(); i++) {
                if (mGroupsData.get(i).getGroupId().equals(airSession.getChannel().getId())) {
                    mGroupsData.get(i).setWhoIsTalking("");
                    mGroupsData.get(i).setShowTalking(false);
                    mView.updateList(mGroupsData);
                }
            }
        }
    }

    public void onMediaStateListen(AirSession airSession, AirContact airContact) {
        Sound.playSound(Sound.PLAYER_MEDIA_OTHER_ON, mActivity);
        //接受别人讲话开始
        for (int i = 0; i < mGroupsData.size(); i++) {
            if (mGroupsData.get(i).getGroupId().equals(airSession.getChannel().getId())) {
                mGroupsData.get(i).setWhoIsTalking(airSession.getSpeaker().getDisplayName() + "正在讲话");
                mGroupsData.get(i).setShowTalking(true);
                mView.updateList(mGroupsData);
//                mAdapter.notifyDataSetChanged();
            }
        }
    }

    public void onMediaStateListenEnd(AirSession airSession) {
        Sound.playSound(Sound.PLAYER_MEDIA_OTHER_OFF, mActivity);
        //接受别人讲话结束
        for (int i = 0; i < mGroupsData.size(); i++) {
            if (mGroupsData.get(i).getGroupId().equals(airSession.getChannel().getId())) {
                mGroupsData.get(i).setWhoIsTalking("");
                mGroupsData.get(i).setShowTalking(false);
                mView.updateList(mGroupsData);
//                mAdapter.notifyDataSetChanged();
            }
        }

    }

    //-------------------------------MediaListener

    /**
     * 发起群组列表的刷新
     */
    private void onUpdateGroupList() {
//        mView.showLoading();
        /**
         * 由于在群组创建的时候有重新设置过监听，所以暂时先放在这边处理
         * 但是每次刷新列表的时候都设置监听是不大合理的，需完善
         */
        setAirtalkeeChannel();
        mPocAirtalkeeChannel.getChannelList(AirtalkeeChannel.CHANNEL_TYPE_SECRET);
    }

    /**
     * 刷新群组Item：比如有人在对讲时，Item显示 xxx正在对讲
     *
     * @param airSession
     */
    private void onUpdateGroupItem(AirSession airSession) {
        if (null == airSession) {
            ALog.e("onUpdateGroupItem param -> airSession is null");
            return;
        }
        //TODO 是否可单独对应的响应Item做刷新就好？
    }

    /**
     * 初始化群组相关并刷新群组数据
     */
    private void initPocAirtalkeeChannel() {
        mPocAirtalkeeChannel = PocAirtalkeeChannel.getPocAirtalkeeChannelInstance();

        UpdateGroupBean bean = new UpdateGroupBean();
        bean.setCurrentEvent(UpdateGroupBean.EVENT_GROPULIST_UPDATE);
        bean.setTarget(this.getClass(), this.getClass(), "onEventBusUpdateGroups");
        onEventBusUpdateGroups(bean);
    }

    public void setAirtalkeeChannel() {
        mPocAirtalkeeChannel.setOnChannelListener(this);
    }

    /**
     * 初始化群组列表数据
     * 1、旧数据，保存原数据存放在列表中
     * 2、新数据，则实例出来并存放进列表中
     *
     * @param channelList
     */
    private void initData(List<AirChannel> channelList) {
//        mLockedGroupBean = null;
        if (mGroupsData == null) {
            mGroupsData = new ArrayList<>();
        } else {
            mGroupsData.clear();
        }
        if (mGroupsCreateData == null) {
            mGroupsCreateData = new ArrayList<>();
        } else {
            mGroupsCreateData.clear();
        }
        for (int i = 0; i < channelList.size(); i++) {
            AirChannel airChannel = channelList.get(i);
            if (airChannel == null) {
                continue;
            }
            filterCreateGroups(airChannel);
            boolean hasInData = false;
            if (mChannelListeningData != null && mChannelListeningData.size() > 0) {
                for (int j = 0; j < mChannelListeningData.size(); j++) {
                    GroupBean bean = mChannelListeningData.get(j);
                    if (bean == null) {
                        continue;
                    }
                    if (bean.getGroupId().equals(airChannel.getId())) {
                        initLockedChanneled(airChannel, bean);
                        bean.setGroupName(airChannel.getDisplayName());
                        mGroupsData.add(bean);
                        hasInData = true;
                        break;
                    }
                }
            }
            if (hasInData) {
                continue;
            }

            GroupBean groupBean = new GroupBean();
            groupBean.setGroupName(airChannel.getDisplayName());
            groupBean.setGroupId(airChannel.getId());
            groupBean.setListen(false);
            groupBean.setIsLocked(false);
            groupBean.setShowTalking(false);
            groupBean.setCreater(airChannel.getCreatorId().equals(mUserId));
            groupBean.setMemberTotalCount(airChannel.getMemberCount() + "");
            groupBean.setMemberOnlineCount(airChannel.getOnlineNumber() + "");
            initLockedChanneled(airChannel, groupBean);
            mGroupsData.add(groupBean);
        }
    }

    /**
     * 过滤当前频道是否为当前账号创建的
     *
     * @param airChannel
     */
    private void filterCreateGroups(AirChannel airChannel) {
        if (!airChannel.getCreatorId().equals(mUserId)) {
            return;
        }
        GroupSelectBean bean = new GroupSelectBean();
        bean.setGroupName(airChannel.getDisplayName());
        bean.setGroupId(airChannel.getId());
        bean.setSelectStatus(false);
        mGroupsCreateData.add(bean);
    }

    /**
     * 应用启动时初始化是否有上锁频道
     *
     * @param airChannel
     * @param bean
     */
    private void initLockedChanneled(AirChannel airChannel, GroupBean bean) {
        if (airChannel.getSession().getSessionCode().equals(lockedChannel)) {
            bean.setIsLocked(false);
            setChannelLocked(bean);
        }
    }

    @Override
    ArrayList<GroupBean> getChannelListeningList() {
        return mChannelListeningData;
    }

    public ArrayList<GroupSelectBean> getGroupsCreateData() {
        if (mGroupsCreateData == null) {
            mGroupsCreateData = new ArrayList<>();
        }
        return mGroupsCreateData;
    }

    @Override
    void setChannelListened(GroupBean bean) {
        if (bean.isListen()) {
            deleteFromSessionList(bean);
            if (bean.getAirSession() != null) {
                mPocAirtalkeeSessionManager.sessionBye(bean.getAirSession());
                /**
                 * @author sudf
                 * @data 2017.9.7
                 * bug：首次监听频道正常，取消监听在恢复监听时，没有实际监听
                 * 原因：取消监听的时候，没有对bean中的airsession置空，导致设置时判断airsession不为空，从而没有重新sessionCall
                 */
                bean.setAirSession(null);
            }
            if (bean.isLocked()) {
                bean.setIsLocked(false);
                mPocAirtalkeeSessionManager.setLockedAirSession(null, mActivity);
//                LocationReportChannelBean b = new LocationReportChannelBean();
//                b.setCurChannelEvent(LocationReportChannelBean.CHANNEL_EVENT_ENTER);
//                b.setLockGroupId("");
//                EventBus.getDefault().post(b);
            }
        } else {
            if (mChannelListeningData.size() >= SESSION_MAX_COUNT) {
                Toast.makeText(mActivity, mActivity.getString(R.string.tip_listeningchannel_max), Toast.LENGTH_SHORT).show();
            } else {
                if (bean.getAirSession() == null) {
                    AirSession airSession = mPocAirtalkeeSessionManager.sessionCall(bean.getGroupId());
                    bean.setAirSession(airSession);
                }
                addToSessionList(bean);
            }
        }
    }

    @Override
    void setChannelLocked(GroupBean bean) {
        if (!bean.isListen() && mChannelListeningData.size() >= SESSION_MAX_COUNT) {
            Toast.makeText(mActivity, mActivity.getString(R.string.tip_listeningchannel_max), Toast.LENGTH_SHORT).show();
            return;
        }
        if (bean.isLocked()) {//如果当前是上锁状态，那么取消掉
            mPocAirtalkeeSessionManager.setLockedAirSession(null, mActivity);
            bean.setIsLocked(false);
//            LocationReportChannelBean b = new LocationReportChannelBean();
//            b.setCurChannelEvent(LocationReportChannelBean.CHANNEL_EVENT_ENTER);
//            b.setLockGroupId("");
//            EventBus.getDefault().post(b);
        } else {
            changeLocked(bean);
            if (bean.getAirSession() == null) {
                AirSession airSession = mPocAirtalkeeSessionManager.sessionCall(bean.getGroupId());
                bean.setAirSession(airSession);
            }
            mPocAirtalkeeSessionManager.setLockedAirSession(bean.getAirSession(), mActivity);

//            /**
//             * 将锁定的频道传到LocationReportService进行位置上传
//             */
//            LocationReportChannelBean b = new LocationReportChannelBean();
//            b.setCurChannelEvent(LocationReportChannelBean.CHANNEL_EVENT_ENTER);
//            b.setLockGroupId(bean.getGroupId());
//            EventBus.getDefault().post(b);
        }
    }

    @Override
    boolean checkVipStatus(int groupsCount) {
        int vipStatus = (int) SPUtil.get(mActivity, SPUtil.SPKeyGlobal.KEY_VIP_STATUS, 0);
        ALog.d("vipStatus = %s,groupsCount = %s", vipStatus, groupsCount);
        /**
         * 账号状态，目前只有：普通会员账号、Vip会员账号、
         * @param vipStatus {@code 0} 普通账号,{@code 2} 会员账号<br/>
         * 备注：普通会员创建群主上限5个
         */
        if (vipStatus == 2) {
            return true;
        } else {
            if (groupsCount > 5) {
                return false;
            }
            return true;
        }
    }

    @Override
    void modifyGroupName(String groupId, String newName) {

        mModel.modifyGroupName(groupId, newName, new HttpCallbackImpl<BaseBean>() {

            @Override
            public void onStart() {
                if (mView == null) {
                    return;
                }
                mView.showLoading(mActivity.getString(R.string.tip_modifying));
            }

            @Override
            public void onSuccess(BaseBean bean) {
                ALog.d("code = %s,desc = %s", bean.getCode(), bean.getDesc());
                UpdateGroupBean updateGroupBean = new UpdateGroupBean();
                updateGroupBean.setCurrentEvent(UpdateGroupBean.EVENT_GROPULIST_UPDATE);
                updateGroupBean.setTarget(this.getClass(), GroupsPresenterImpl.class, "onEventBusUpdateGroups");
                onEventBusUpdateGroups(updateGroupBean);
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                if (mView == null) {
                    return;
                }
                ALog.d("code = %s,message = %s", bean.getCode(), bean.getDesc());
                mView.showNetError(bean.getDesc());
            }

            @Override
            public void onFinish() {
                if (mView == null) {
                    return;
                }
                mView.dismissLoading();
            }
        });
    }

    /**
     * 频道上锁：
     * 1、上锁状态：如果已经有其他频道上锁，则清除其上锁状态，对当前选择的频道进行上锁
     * 2、如果当前频道不处于监听状态，则对其设置监听状态
     *
     * @param bean
     */
    private void changeLocked(GroupBean bean) {
        for (int i = 0; i < mGroupsData.size(); i++) {
            if (mGroupsData.get(i).isLocked()) {
                mGroupsData.get(i).setIsLocked(false);
                break;
            }
        }
        bean.setIsLocked(true);
        if (bean.isListen()) {
            return;
        }
        addToSessionList(bean);
    }

    /**
     * 对频道设置监听状态
     *
     * @param bean
     */
    private void addToSessionList(GroupBean bean) {
        bean.setListen(true);
        if (mChannelListeningData.size() >= 5) {
            return;
        }
        mChannelListeningData.add(bean);
        /**
         * 将监听的频道传到LocationReportService进行位置上传
         */
        LocationReportChannelBean b = new LocationReportChannelBean();
        b.setCurChannelEvent(LocationReportChannelBean.CHANNEL_EVENT_LISTEN);
        b.setListenChannelList(mChannelListeningData);
        EventBus.getDefault().post(b);
    }

    /**
     * 移除监听频道
     *
     * @param bean
     */
    private void deleteFromSessionList(GroupBean bean) {
        bean.setListen(false);
        mChannelListeningData.remove(bean);
        /**
         * 将监听的频道传到LocationReportService进行位置上传
         */
        LocationReportChannelBean b = new LocationReportChannelBean();
        b.setCurChannelEvent(LocationReportChannelBean.CHANNEL_EVENT_LISTEN);
        b.setListenChannelList(mChannelListeningData);
        EventBus.getDefault().post(b);
    }

}
